# File: src/mcp_server/tools/web_automation_tools.py
# Purpose: Defines MCP tools that wrap the web automation skills.

import logging
from typing import Optional

# Import the 'mcp' instance defined in src/mcp_server/app.py
# *** Corrected import path ***
from ..app import mcp

# Import schemas
from ...schemas.mcp.web_automation import (
    NavigateParams, ClickElementParams, TypeTextParams, ObservePageParams,
    GetTextContentParams, PageObservation
)
from ...schemas.common import StatusResponse
# Import skill functions
from ...skills.web_automation import actions as web_skill_actions
# Import exceptions
from ...core.exceptions import SkillError
# Import context helper and type hint
from ..context import Context, get_server_context, ServerContext # Make sure ServerContext is imported if needed

# Use core logger setup
from ...core.logging_setup import get_logger
logger = get_logger(__name__)


@mcp.tool()
async def navigate(ctx: Context, params: NavigateParams) -> StatusResponse:
    """MCP Tool: Navigates the browser to the specified URL."""
    tool_name = "navigate"
    # Example of accessing lifespan context if needed (not strictly necessary for navigate)
    # server_context: ServerContext = get_server_context(ctx)
    # logger.debug(f"Lifespan start message: {server_context.start_message}") # Example access
    logger.info(f"MCP Tool '{tool_name}' called with URL: {params.url}")
    try:
        status_message = await web_skill_actions.navigate_to_url(url=params.url)
        return StatusResponse(success=True, message=status_message, details=None)
    except SkillError as e:
        logger.error(f"SkillError in '{tool_name}' tool: {e}", exc_info=False)
        return StatusResponse(success=False, message=str(e), details=None)
    except Exception as e:
        logger.error(f"Unexpected error in '{tool_name}' tool: {e}", exc_info=True)
        return StatusResponse(success=False, message="Internal server error during navigation.", details=None)

@mcp.tool()
async def observe_page(ctx: Context, params: Optional[ObservePageParams] = None) -> PageObservation:
    """MCP Tool: Observes the current web page state."""
    tool_name = "observe_page"
    focus_selector = params.focus_selector if params else None
    logger.info(f"MCP Tool '{tool_name}' called. Focus selector: '{focus_selector}'")
    try:
        observation_result = await web_skill_actions.observe_page(focus_selector=focus_selector)
        if observation_result.error_message:
             logger.warning(f"'{tool_name}' skill reported errors: {observation_result.error_message}")
        return observation_result
    except SkillError as e:
        logger.error(f"SkillError in '{tool_name}' tool: {e}", exc_info=False)
        return PageObservation(
            url=None, title=None, focused_text=None, interactable_elements=[],
            error_message=str(e), observation_summary=None
        )
    except Exception as e:
        logger.error(f"Unexpected error in '{tool_name}' tool: {e}", exc_info=True)
        return PageObservation(
            url=None, title=None, focused_text=None, interactable_elements=[],
            error_message=f"Internal server error during page observation: {e}",
            observation_summary=None
        )

@mcp.tool()
async def click_element(ctx: Context, params: ClickElementParams) -> StatusResponse:
    """MCP Tool: Clicks an element identified by its agent_id."""
    tool_name = "click_element"
    logger.info(f"MCP Tool '{tool_name}' called for element_id: {params.element_id}")
    try:
        status_message = await web_skill_actions.click_element(element_id=params.element_id)
        return StatusResponse(success=True, message=status_message, details=None)
    except SkillError as e:
        logger.error(f"SkillError in '{tool_name}' tool: {e}", exc_info=False)
        return StatusResponse(success=False, message=str(e), details=None)
    except Exception as e:
        logger.error(f"Unexpected error in '{tool_name}' tool: {e}", exc_info=True)
        return StatusResponse(success=False, message="Internal server error during click.", details=None)

@mcp.tool()
async def type_text(ctx: Context, params: TypeTextParams) -> StatusResponse:
    """MCP Tool: Types text into an element identified by its agent_id."""
    tool_name = "type_text"
    log_text = (params.text_to_type[:30] + "...") if len(params.text_to_type) > 30 else params.text_to_type
    logger.info(f"MCP Tool '{tool_name}' called for element_id: {params.element_id}. Text: '{log_text}'. Clear: {params.clear_first}")
    try:
        status_message = await web_skill_actions.type_text(
            element_id=params.element_id,
            text_to_type=params.text_to_type,
            clear_first=params.clear_first
        )
        return StatusResponse(success=True, message=status_message, details=None)
    except SkillError as e:
        logger.error(f"SkillError in '{tool_name}' tool: {e}", exc_info=False)
        return StatusResponse(success=False, message=str(e), details=None)
    except Exception as e:
        logger.error(f"Unexpected error in '{tool_name}' tool: {e}", exc_info=True)
        return StatusResponse(success=False, message="Internal server error during typing.", details=None)

@mcp.tool()
async def get_text_content(ctx: Context, params: Optional[GetTextContentParams] = None) -> StatusResponse:
    """MCP Tool: Gets text content from page or selector."""
    tool_name = "get_text_content"
    selector = params.selector if params else None
    logger.info(f"MCP Tool '{tool_name}' called for selector: '{selector or '<body>'}'")
    try:
        extracted_text = await web_skill_actions.get_text_content(selector=selector)
        # Return text in message field, explicit details=None
        return StatusResponse(success=True, message=extracted_text, details=None)
    except SkillError as e:
         logger.error(f"SkillError in '{tool_name}' tool: {e}", exc_info=False)
         return StatusResponse(success=False, message=str(e), details=None)
    except Exception as e:
        logger.error(f"Unexpected error in '{tool_name}' tool: {e}", exc_info=True)
        return StatusResponse(success=False, message="Internal server error getting text content.", details=None)

logger.debug("Web automation MCP tools registered.")